function _request(url, params, body, method) {
    let controller = new AbortController();
    var signal = controller.signal;
    let uri = new URLSearchParams();
    if(params) {
        for(let s in params) {
            uri.set(s, params[s]);
        }
    }
    let urls = `${url}?${uri.toString()}`;
    if(method === 'GET') {
        return fetch(urls, {
            method,
            signal
        }).then(res => Promise.all([res.ok, res.status, res.json()])).then(([ok, status, json]) => {
            if(ok) {
                json.controller = controller;
                return json;
            } else {
                throw new Error(json.error)
            }
        }).catch(error => {
            throw error;
        });
    }
    if(method === 'POST') {
        return fetch(urls, {
            method,
            signal,
            body: JSON.stringify(body),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => Promise.all([res.ok, res.status, res.json()])).then(([ok, status, json]) => {
            if(ok) {
                json.controller = controller;
                return json;
            } else {
                throw new Error(json.error)
            }
        }).catch(error => {
            throw error;
        });
    }
}

// get suo
export function getSuo(content) {
  let m = content.match(/suo(.+?)\)/i)
  return m ? m[1].slice(2) : 'https://wx4.sinaimg.cn/mw690/0060lm7Tly1fvmtrka9p5j30b40b43yo.jpg'
}

export function get(url, params) {
    return _request(url, params, null, 'GET');
}

export function post(url, body = {}, params) {
    return _request(url, params, body, 'POST');
}

export function preData(data) {
    if(data.posts) {
        data.posts.forEach(post => {
            let arr = post.content.split('#');
            post.text = typeof arr[1] === 'string' ? arr[1].replace('简介', '').replace('>', '') : arr[1];
            post.img = getSuo(post.content);
            let s1 = post.content.match(/(第\d+话)/) ? post.content.match(/(第\d+话)/)[0] : null;
            post.desc = s1 ? s1.match(/\d+/)[0] : 0; // 第几话
        });
    } else {
        let arr = data.result.content.split('#');
        data.result.text = typeof arr[1] === 'string' ? arr[1].replace('简介', '').replace('>', '') : arr[1];
        data.result.img = getSuo(data.result.content);
        let s1 = data.result.content.match(/(第\d+话)/) ? data.result.content.match(/(第\d+话)/)[0] : null;
        data.result.desc = s1 ? s1.match(/\d+/)[0] : 0; // 第几话
    }
    return data;
}

export function preget(url, params) {
    return get(url, params).then(res => preData(res));
}

export function prepost(url, body = {}, params) {
    return post(url, body, params).then(res => preData(res));
}